package com.handpay.nocardpay.baselibrary.onlinemarket.view.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.commbase.view.widget.CustomShowDialog;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.onlinemarket.model.bean.MarketOrderDetailBean;
import com.handpay.nocardpay.baselibrary.onlinemarket.presenter.MarketOrderDetailPresenter;
import com.handpay.nocardpay.baselibrary.onlinemarket.view.IOnlineMarketView;
import com.handpay.nocardpay.baselibrary.onlinemarket.view.widget.MoneyEditText;
import com.handpay.nocardpay.baselibrary.pay.unipay.view.fragment.NoCardPayFragment;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ArithUtil;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.Heart;
import com.handpay.nocardpay.baselibrary.utils.MD5;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lyang on 2018/1/15.
 */

public class OnlineMarketFragment extends BaseFragment implements IOnlineMarketView {
    public static final int ONLINE_MARKET_FRAGMENT_REQUEST_CODE = 1;
    public static final int ONLINE_MARKET_FRAGMENT_RESULT_OK_CODE = 1;

    public static final String MIN_AMOUNT_KEY = "MIN_AMOUNT_KEY";
    public static final String URL_KEY = "URL_KEY";

    private CustomShowDialog mCustomShowDialog;
    private double mMinAmount;
    private String mURL;
    private WebView mWebView;
    private MarketOrderDetailPresenter mMarketOrderDetailPresenter;
    private MoneyEditText amount_et;
    private ImageView btn_goToFunction;

    public static OnlineMarketFragment newInstance(double min_amount,String url_key) {
        Bundle args = new Bundle();
        args.putDouble(MIN_AMOUNT_KEY, min_amount);
        args.putString(URL_KEY, url_key);
        OnlineMarketFragment fragment = new OnlineMarketFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView(View view) {
        mWebView = (WebView) view.findViewById(R.id.wv_content);
        // 开启 localStorage
        mWebView.getSettings().setDomStorageEnabled(true);
        // 设置支持javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 启动缓存
        mWebView.getSettings().setAppCacheEnabled(true);
        // 设置缓存模式
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        //使用自定义的WebViewClient
        mWebView.setWebViewClient(new WebViewClient() {
            //覆盖shouldOverrideUrlLoading 方法
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("closewindow")) {
                    pop();
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        });
        btn_goToFunction =(ImageView)  view.findViewById(R.id.btn_goToFunction);
    }

    @Override
    public void initListener() {
        btn_goToFunction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mMinAmount = getArguments().getDouble(MIN_AMOUNT_KEY);
        String mallUrl  =getArguments().getString(URL_KEY);
        mMarketOrderDetailPresenter = new MarketOrderDetailPresenter(this, _mActivity);
//        String host = null;
//        if (TextUtils.isEmpty(mURL)){
//             host = NoCardPayConfig.ONLINE_MARKET_URL;
//        }else {
//            host = mURL;
//        }
//        String mallUrl = host + "?merchantCode=" + AccountUtils.getMerchantCode(_mActivity);
        mWebView.loadUrl(mallUrl);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                HPLog.i(HPLog.YL_TAG, "MarketOrderDetailBean url: " + url);
                if (url.startsWith("http://handpay/orderPayment")) {
                    //supplierCode=xxx&orderID=xxx&orderTime=xxx&signData=xxx";
                    Map<String, String> map = CommonUtils.getUrlParamsMap(url);
                    String supplierCode = map.get("supplierCode");
                    String orderID = map.get("orderID");
                    String orderTime = map.get("orderTime");
                    String signData = map.get("signData");
                    String key = supplierCode + "|" + orderID + "|" + orderTime + "|" + AccountUtils.getAccountName(_mActivity);
                    String token = MD5.toMD5(key);
                    if (signData.equals(token)) {
                        doMarketOrderDetailByOrderId(orderID, orderTime);
                    }
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_online_market;
    }

    /**
     * 获取订单信息
     *
     * @param orderID   订单ID
     * @param orderTime 订单时间
     */
    public void doMarketOrderDetailByOrderId(String orderID, String orderTime) {
        HashMap<String, Object> paramers = new HashMap<String, Object>();
        paramers.put("orderID", SecureManager.getInstance().des(orderID, 1, null)); // 交易流水
        paramers.put("orderTime", SecureManager.getInstance().des(orderTime, 1, null)); // 交易流水
        mMarketOrderDetailPresenter.getMarketOrderDetail(paramers, MarketOrderDetailBean.class, true);
    }

    @Override
    public void onMarketOrderDetailSuccess(MarketOrderDetailBean marketOrderDetail) {
        HPLog.i(HPLog.YL_TAG, "MarketOrderDetailBean:" + marketOrderDetail.toString());
        String orderNo = SecureManager.getInstance().des(marketOrderDetail.getOrderNo(), 0, null);
        String amount = SecureManager.getInstance().des(marketOrderDetail.getAmount(), 0, null);
        String transSeq = SecureManager.getInstance().des(marketOrderDetail.getTransSeq(), 0, null);
        String goodsName = SecureManager.getInstance().des(marketOrderDetail.getGoodsName(), 0, null);
        if (mCustomShowDialog == null) {
            mCustomShowDialog = new CustomShowDialog(_mActivity, R.layout.layout_dialog_online_market, R.style.DialogSlideAnim);
            Window window = mCustomShowDialog.getDialog().getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setBackgroundDrawableResource(android.R.color.transparent);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = Heart.displayWidthPixels;
            window.setAttributes(lp);
            mCustomShowDialog.setDialogCallback(new CustomShowDialog.DialogCallback() {
                @Override
                public void onClickButtonOK() {
                    if (TextUtils.isEmpty(amount_et.getText())) {
                        DialogUtils.showToast(_mActivity, getString(R.string.please_input_no_card_pay_alert));
                        return;
                    }
                    Double selectAmount = Double.valueOf(amount_et.getText().toString());
                    amount_et.setText(CommonUtils.formatMoneyDouble(selectAmount));
                    if (ArithUtil.mul(selectAmount, 100d) < mMinAmount) {
                        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.min_no_card_pay_alert, mMinAmount / 100));
                        return;
                    }
                    startForResult(NoCardPayFragment.newInstance(ArithUtil.mul(selectAmount, 100d)),ONLINE_MARKET_FRAGMENT_REQUEST_CODE);
                    mCustomShowDialog.dismiss();
                }

                @Override
                public void onClickButtonCancel() {
                    mCustomShowDialog.dismiss();
                }
            });
        }
        TextView goods_name_tv = (TextView) mCustomShowDialog.getDialog().findViewById(R.id.goods_name_tv);
        amount_et = (MoneyEditText) mCustomShowDialog.getDialog().findViewById(R.id.amount_et);
        TextView order_no_tv = (TextView) mCustomShowDialog.getDialog().findViewById(R.id.order_no_tv);
        amount_et.setText("");
        goods_name_tv.setText(goodsName);
        order_no_tv.setText(orderNo);
        mCustomShowDialog.show();
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (ONLINE_MARKET_FRAGMENT_REQUEST_CODE == requestCode) {
            pop();
        }
    }
}
